import type {RouteRecordRaw} from 'vue-router'
import {createRouter, createWebHistory} from 'vue-router'
import {useUserStore} from '@/stores/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 配置NProgress
NProgress.configure({ showSpinner: false })

// 路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/layout/index.vue'),
    redirect: '/dashboard',
    meta: {
      title: '首页',
      requiresAuth: true
    },
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: {
          title: '仪表盘',
          requiresAuth: true
        }
      },
      {
        path: '/user',
        name: 'User',
        component: () => import('@/views/user/index.vue'),
        meta: {
          title: '用户管理',
          requiresAuth: true
        }
      },
      {
        path: '/codegen',
        name: 'Codegen',
        meta: {
          title: '代码生成',
          requiresAuth: true
        },
        children: [
          {
            path: '/codegen/service',
            name: 'CodegenService',
            component: () => import('@/views/codegen/service/index.vue'),
            meta: {
              title: '服务生成',
              requiresAuth: true
            }
          },
        {
          path: '/codegen/table-manager',
          name: 'TableManager',
          component: () => import('@/views/codegen/TableManager/TableManager.vue'),
          meta: {
            title: '表管理',
            requiresAuth: true
          }
        },
          {
            path: '/codegen/datasource',
            name: 'CodegenDatasource',
            component: () => import('@/views/codegen/datasource/index.vue'),
            meta: {
              title: '数据源管理',
              requiresAuth: true
            }
          }
        ]
      },
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue'),
    meta: {
      title: '页面不存在'
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  
  const userStore = useUserStore()
  const token = userStore.token
  
  // 设置页面标题
  document.title = to.meta?.title ? `${to.meta.title} - WZH微服务管理系统` : 'WZH微服务管理系统'
  
  // 如果是登录页面
  if (to.path === '/login') {
    if (token) {
      // 已登录，跳转到首页
      next('/')
    } else {
      next()
    }
    return
  }
  
  // 需要认证的页面
  if (to.meta?.requiresAuth) {
    if (!token) {
      // 未登录，跳转到登录页
      next('/login')
      return
    }
    
    // 检查用户信息
    if (!userStore.userInfo) {
      try {
        await userStore.getUserInfo()
      } catch (error) {
        // 获取用户信息失败，清除token并跳转到登录页
        userStore.logout()
        next('/login')
        return
      }
    }
  }
  
  next()
})

router.afterEach(() => {
  NProgress.done()
})

export default router